package com.example.musicplayer.dao

import android.annotation.SuppressLint
import android.content.Context
import com.example.musicplayer.model.SongCategory
import com.example.musicplayer.util.CategoryDatabaseHelper

class CategoryDAO(private val context: Context) {

    val dbHelper = CategoryDatabaseHelper(context)

    @SuppressLint("Range")
    fun getAllSongCategories(): List<SongCategory> {
        val songCategories = mutableListOf<SongCategory>()
        val db = dbHelper.readableDatabase
        val cursor = db.query(
            CategoryDatabaseHelper.TABLE_SONG_CATEGORY,
            arrayOf(CategoryDatabaseHelper.COLUMN_CATEGORY_ID, CategoryDatabaseHelper.COLUMN_CATEGORY_NAME),
            null, null, null, null, null
        )
        while (cursor.moveToNext()) {
            val id = cursor.getInt(cursor.getColumnIndex(CategoryDatabaseHelper.COLUMN_CATEGORY_ID))
            val name = cursor.getString(cursor.getColumnIndex(CategoryDatabaseHelper.COLUMN_CATEGORY_NAME))
            songCategories.add(SongCategory(id, name))
        }
        cursor.close()
        db.close()
        return songCategories
    }

    @SuppressLint("Range")
    fun getSongCategoryById(categoryId: Int): SongCategory? {
        val db = dbHelper.readableDatabase
        val cursor = db.query(
            CategoryDatabaseHelper.TABLE_SONG_CATEGORY,
            arrayOf(CategoryDatabaseHelper.COLUMN_CATEGORY_ID, CategoryDatabaseHelper.COLUMN_CATEGORY_NAME),
            "${CategoryDatabaseHelper.COLUMN_CATEGORY_ID} = ?",
            arrayOf(categoryId.toString()),
            null, null, null
        )
        var songCategory: SongCategory? = null
        if (cursor.moveToFirst()) {
            val id = cursor.getInt(cursor.getColumnIndex(CategoryDatabaseHelper.COLUMN_CATEGORY_ID))
            val name = cursor.getString(cursor.getColumnIndex(CategoryDatabaseHelper.COLUMN_CATEGORY_NAME))
            songCategory = SongCategory(id, name)
        }
        cursor.close()
        db.close()
        return songCategory
    }
}